package nl.infodation.emr.pricingservice.ui;

import java.util.ArrayList;
import java.util.List;

import nl.infodation.emr.pricingservice.entity.DomainListSetting;
import nl.infodation.emr.pricingservice.entity.DomainRule;
import nl.infodation.emr.pricingservice.ui.component.ExplicitPagingContainer;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.Constants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gwt.cell.client.DateCell;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Table;

@SuppressWarnings({"rawtypes", "unchecked"})
public class DomainRuleList extends Table {
	
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(DomainRuleList.class);
	final private ExplicitPagingContainer pagingContainer = new ExplicitPagingContainer();
	private final static List<Long> activeList = new ArrayList<Long>();

	public static List<Long> getActiveList() {
		return activeList;
	}
	
	private ActiveDomainRuleListView parentView;

	public Object[] STANDARD_COL_NAME;
	
	public String[] STANDARD_COL_HEADER;
	
	private void initColumnData() {
		STANDARD_COL_NAME = new Object[] {
				"choise", "ruleId", "ruleName", "description", "busLine", "country",
				"beginDate", "endDate",
			};
		
		STANDARD_COL_HEADER = new String[] {
				SessionData.getI18N().getMessage(Constants.CHOISE_HEADER),
				SessionData.getI18N().getMessage(Constants.RULE_ID_HEADER),
				SessionData.getI18N().getMessage(Constants.RULE_NAME_HEADER),
				SessionData.getI18N().getMessage(Constants.DESCRIPTION_HEADER),
				SessionData.getI18N().getMessage(Constants.BUS_LINE_HEADER),
				SessionData.getI18N().getMessage(Constants.COUNTRY_HEADER),
				SessionData.getI18N().getMessage(Constants.BEGIN_DATE_HEADER),
				SessionData.getI18N().getMessage(Constants.END_DATE_HEADER),
			};
	}
	
	public DomainRuleList() {
		this.doInitalization();
	}
	
	public DomainRuleList(ActiveDomainRuleListView parentView){
		this.doInitalization();
		this.setParentView(parentView);
	}

	public void doInitalization() {
		initColumnData();
		setSizeFull();
		initializePagingContainer();
		setContainerDataSource(pagingContainer);
		setVisibleColumns(STANDARD_COL_NAME);
        setColumnHeaders(STANDARD_COL_HEADER);
        setColumnCollapsingAllowed(true);
        setColumnReorderingAllowed(true);
        setSelectable(true);
        setImmediate(true);
        setNullSelectionAllowed(false);
        addGeneratedColumn();
	}
	public void setColumWidth(DomainListSetting setting) {
		this.setColumnWidth(STANDARD_COL_NAME[0], setting.getChoise());
		this.setColumnWidth(STANDARD_COL_NAME[1], setting.getRuleId());
		this.setColumnWidth(STANDARD_COL_NAME[2], setting.getRuleName());
		this.setColumnWidth(STANDARD_COL_NAME[3], setting.getDescription());
		this.setColumnWidth(STANDARD_COL_NAME[4], setting.getBusLine());
		this.setColumnWidth(STANDARD_COL_NAME[5], setting.getCountry());
		this.setColumnWidth(STANDARD_COL_NAME[6], setting.getBeginDate());
		this.setColumnWidth(STANDARD_COL_NAME[7], setting.getEndDate());
	}
	
	public int getItemCount() {
		return pagingContainer.getItemCount();
	}
	
	private void addGeneratedColumn() {
		addGeneratedColumn("choise", new BooleanColumnGenerator());
	}
	
    class BooleanColumnGenerator implements ColumnGenerator, ClickListener {
        
		private static final long serialVersionUID = 1L;

		public Object generateCell(Table source, Object itemId, Object columnId) {
			final BeanItem beanItem =  (BeanItem)source.getItem(itemId);
        	
        	String debugId = null;
        	long id = -1;
        	
				DomainRule p = (DomainRule)beanItem.getBean();
				debugId = p.getDomainRuleId().toString();
				id = p.getDomainRuleId();
				

            final CheckBox chbChoise = new CheckBox("", false);
            
			ObjectProperty property = new ObjectProperty(false, Boolean.class);
            Item item = source.getItem(itemId);
            item.addItemProperty(columnId, property);
			
			chbChoise.setPropertyDataSource(property);
            chbChoise.setDebugId(debugId);
            chbChoise.setImmediate(true);
            chbChoise.addListener(this);
            
            //set value for checkbox
            if (DomainRuleList.getActiveList().contains(id)) {
            	property.setValue(true); //chkChoise is checked
            }
            
            return chbChoise;
        }
		@Override
    	public void buttonClick(ClickEvent event) {
    		final Button source = event.getButton();

    		if (source instanceof CheckBox) {
    			CheckBox box = (CheckBox)source;
    			boolean enabled = event.getButton().booleanValue();
				try {
					long promotionId = Long.parseLong(box.getDebugId());
					activeList.remove(promotionId);
					if (enabled) {
						activeList.add(promotionId);
					}
					
					// Set show/hide actions on screen for user clear
					if (activeList.size() == 0) {
						parentView.setEnableCheckedRule(false);
						
					} else {
						parentView.setEnableCheckedRule(true);
					}
				} catch (NumberFormatException numberFormatException) {
					LOG.debug(box.getDebugId() + " cann't parse to Long type", numberFormatException);
					LOG.error("Cann't stick/unstick the checkbox!");
				}
    			
    		}
    	}
    }
    	
	private void initializePagingContainer() {
		pagingContainer.setPageSize(20);
		
		pagingContainer.addContainerProperty("choise", Boolean.class, null);
		pagingContainer.addContainerProperty("DomainRuleId", String.class, null);
		pagingContainer.addContainerProperty("ruleId", String.class, null);
		pagingContainer.addContainerProperty("ruleName", String.class, null);
		pagingContainer.addContainerProperty("description", String.class, null);
		pagingContainer.addContainerProperty("descriptionId", String.class, null);
		pagingContainer.addContainerProperty("salience", int.class, null);
		pagingContainer.addContainerProperty("busLine", String.class, null);
		pagingContainer.addContainerProperty("country", String.class, null);
		pagingContainer.addContainerProperty("beginDate", DateCell.class, null);
		pagingContainer.addContainerProperty("endDate", DateCell.class, null);
		pagingContainer.addContainerProperty("promotionValue", String.class, null);
		pagingContainer.addContainerProperty("channelValue", String.class, null);
		pagingContainer.addContainerProperty("languageValue", String.class, null);
		pagingContainer.addContainerProperty("paymentModeValue", String.class, null);
		pagingContainer.addContainerProperty("shippingModeValue", String.class, null);
		pagingContainer.addContainerProperty("salesIdValue", String.class, null);
		pagingContainer.addContainerProperty("cityTypeValue", String.class, null);
		pagingContainer.addContainerProperty("currencyValue", String.class, null);
		pagingContainer.addContainerProperty("orderAmount", String.class, null);
		pagingContainer.addContainerProperty("lineAmount", String.class, null);
		pagingContainer.addContainerProperty("nbOfItemsPerOrder", String.class, null);
		pagingContainer.addContainerProperty("marketingActionCode", String.class, null);
		pagingContainer.addContainerProperty("familyValue", String.class, null);
		pagingContainer.addContainerProperty("subFamilyValue", String.class, null);
		pagingContainer.addContainerProperty("productCodeValue", String.class, null);
		pagingContainer.addContainerProperty("oneProductForEachSubFamilyValue", String.class, null);
		pagingContainer.addContainerProperty("lotsValue", String.class, null);
		pagingContainer.addContainerProperty("brandValue", String.class, null);
		pagingContainer.addContainerProperty("offerIdValue", String.class, null);
		pagingContainer.addContainerProperty("bundleDefinitionValue", String.class, null);
		pagingContainer.addContainerProperty("commercialRef", String.class, null);
		pagingContainer.addContainerProperty("itemId", String.class, null);
		pagingContainer.addContainerProperty("orderShippingFeeValue", String.class, null);
		pagingContainer.addContainerProperty("orderlineShippingFeeValue", String.class, null);
		pagingContainer.addContainerProperty("orderProposeDiscountValue", String.class, null);
		pagingContainer.addContainerProperty("orderlineSellingPriceValue", String.class, null);
		pagingContainer.addContainerProperty("orderlineDiscountPercentageValue", String.class, null);
		pagingContainer.addContainerProperty("orderlineShippingFeeDiscountPercentageValue", String.class, null);
		pagingContainer.addContainerProperty("family", String.class, null);
		pagingContainer.addContainerProperty("fromSalesupportOffer", String.class, null);
		pagingContainer.addContainerProperty("category", String.class, null);
		pagingContainer.addContainerProperty("ofOrderOffer", String.class, null);
		pagingContainer.addContainerProperty("refco", String.class, null);
		pagingContainer.addContainerProperty("categoryValue", String.class, null);
		pagingContainer.addContainerProperty("shippingDiscountpercentValue", String.class, null);
		pagingContainer.addContainerProperty("orderDiscountPercentValue", String.class, null);
		pagingContainer.addContainerProperty("productIdValue", String.class, null);
	}
	
	public void setDataSource(final List<BeanItem> beans) {
		pagingContainer.setDataSource(beans);
	}
	
	public int getPageSize()
	{
		return pagingContainer.getPageSize();
	}

	public ActiveDomainRuleListView getParentView() {
		return parentView;
	}

	public void setParentView(ActiveDomainRuleListView parentView) {
		this.parentView = parentView;
	}
	
}
